package com.app.util.encrypt;

import java.util.*;
import java.text.DecimalFormat;
import java.io.IOException;
@SuppressWarnings({"unchecked","unused"})
public class Encode {
  DecimalFormat df=new DecimalFormat("##.00");
  DecimalFormat dfs=new DecimalFormat("##.000");

  /**
   * Encode
   * function(功能)：构造函数
   **/
  public Encode() {
  }

  /**
   * 将null转换成""，并且将Object转换成String类型
   * @param Object oTempObject:输入的Object对象
   **/
  public static String nullToBlank(Object oTempObject){
    try{
      if (oTempObject==null){
        return "";
      }
      else{
        return oTempObject.toString();
      }
    }
    catch(Exception e){
    }
    return "";
  }

  public static int nullToZero(Object oTempObject){
	    try{
	      if (oTempObject==null){
	        return 0;
	      }
	      else{
	        return Integer.parseInt(oTempObject.toString());
	      }
	    }
	    catch(Exception e){
	    }
	    return 0;
	  }

  /**
   * 取得ISO8859格式的字符串
   * @param String sInputString:输入的字符串
   **/
  public static String alertCoding(String sInputString) {
    try{
      //如果输入的为null字符串,则转化为空字符串
      if (sInputString==null) sInputString = "";
      byte[] temp_t=sInputString.getBytes("ISO8859-1");
      String temp=new String(temp_t);
      return temp;
    }
    catch (Exception e){
      return "";
    }
  }

  /**
   * 取得GB2312格式的字符串
   * @param String sInputString:输入的字符串
   **/
  public static String getGBEncode(String sInputString) {
    try{
      //如果输入的为null字符串,则转化为空字符串
      if (sInputString==null) sInputString = "";
      byte[] temp_t=sInputString.getBytes("ISO8859-1");
      String temp=new String(temp_t);
      return temp;
    }
    catch (Exception e){
      return "";
    }
  }

  /**
   * 将字符串转换成以HTML格式的字符串
   * @param String sInputString:输入的字符串
   **/
  public static String HtmlEncode(String sInputString){
    String  sTemp="";
    sTemp=replace(sInputString,"&","&amp;");
    sTemp=replace(sTemp,";","&#59");
    sTemp=replace(sTemp,"<","&lt;");
    sTemp=replace(sTemp,">","&gt;");
    sTemp=replace(sTemp,"\r\n","<br>");
    sTemp=replace(sTemp,"\n","<br>");
    sTemp=replace(sTemp," ","&nbsp;");
    sTemp=replace(sTemp,"'","&#39");
    sTemp=replace(sTemp,"\"","&quot;");
    return sTemp;
  }

  /**
   * 将字符串转换成正常格式的字符串
   * @param String sInputString:输入的字符串
   **/
  public static String NoramlEncode(String sInputString){
    String  sTemp="";
    sTemp=replace(sInputString,"&lt;","<");
    sTemp=replace(sTemp,"&gt;",">");
    sTemp=replace(sTemp,"<br>","\r\n");
    sTemp=replace(sTemp,"&nbsp;"," ");
    sTemp=replace(sTemp,"&#39","'");
    sTemp=replace(sTemp,"&amp;","&");
    sTemp=replace(sTemp,"&#59",";");
    sTemp=replace(sTemp,"&quot;","\"");
    return sTemp;
  }

  /**
   * 将SQL字符串进行转换
   * @param String sSQL:输入的SQL字符串
   **/
  public static String sqlEncode(String sSQL){
    //如果输入的SQL语句为null或空字符串,则返回空字符串
    if (sSQL!=null && sSQL.length() == 0) return "";
    int pos = -1;
    int inc = 0;
    StringBuffer tmp = new StringBuffer(sSQL);
    while(pos<=sSQL.length()){
      pos = sSQL.indexOf("'",pos+1);
      if (pos < 0) break;
      else{
        inc++;
        tmp.insert(pos+inc,"'");
      }
    }
    return tmp.toString();
  }



  /**
   *将字符串劈开成数组
   **/
  /*
  Function name:    split
  Description:      将字符串劈开成数组
  Input:            将字符串source劈开成数组div(例子：String TTT[] = my_class.split("aaa:bbb:ccc:ddd",":") ; )
  Output:           数组 (返回值：TTT[0]="aaa"; TTT[1]="bbb"; TTT[2]="ccc"; TTT[3]="ddd"; )
  */
  public static String[] split(String source,String div){
    int arynum = 0,intIdx=0,intIdex=0,div_length = div.length();
    if(source.compareTo("")!=0){
      if(source.indexOf(div)!=-1){
        intIdx = source.indexOf(div);
        for(int intCount =1 ; ; intCount++){
          if(source.indexOf(div,intIdx+div_length)!=-1){
            intIdx= source.indexOf(div,intIdx+div_length);
            arynum = intCount;
          }
          else {arynum+=2;break;}
        }
      }else arynum =1;
    }else arynum = 0;

    intIdx=0;
    intIdex=0;
    String[] returnStr = new String[arynum];

    if(source.compareTo("")!=0){

      if(source.indexOf(div)!=-1){

        intIdx = (int)source.indexOf(div);
        returnStr[0]= (String)source.substring(0,intIdx);

        for(int intCount =1 ; ; intCount++){
          if(source.indexOf(div,intIdx+div_length)!=-1){
            intIdex=(int)source.indexOf(div,intIdx+div_length);

            returnStr[intCount] = (String)source.substring(intIdx+div_length,intIdex);

            intIdx = (int)source.indexOf(div,intIdx+div_length);
          }
          else {
            returnStr[intCount] = (String)source.substring(intIdx+div_length,source.length());
            break;
          }
        }
      }
      else {returnStr[0] = (String)source.substring(0,source.length());return returnStr;}
    }
    else {return returnStr;}
    return returnStr;
  }

  //将字符串按某个分割符分割，返回是一个Vector数组
  public static Vector splitString(String splitStr,String delimiter){
    Vector ts=new Vector();
    StringTokenizer tmpstk=new StringTokenizer(splitStr,delimiter);
    try{
      while(tmpstk.hasMoreTokens()){
        ts.addElement(tmpstk.nextToken());
      }
      return ts;
    }
    catch(Exception e){}
    return null;
  }


  //将str中所有出现tag字符串的地方替换为rep
  public static String replace(String str,String tag,String rep){
	int i=0,j=0,k=0;
    String RETU="";
    String temp=str;
    int tagLen=tag.length();
    while(i<str.length()){
      if(str.substring(i).startsWith(tag)){
        temp=str.substring(j,i)+rep;
        RETU+=temp;
        i+=tagLen;
        j=i;
      }
      else{
        i+=1;
      }
    }
    RETU+=str.substring(j);
    return RETU;
  }



  /**
   * XML内容编码
   * @param s 输入的原始文本内容
   * @return 返回已经编码的XML文本内容
   */
  public static String XMLEncode(String s) {
    String  sTemp;
    sTemp=replace(s,"&","&amp;");
    sTemp=replace(sTemp,"<","&lt;");
    sTemp=replace(sTemp,">","&gt;");
    sTemp=replace(sTemp,"\r\n","&#xD;&#xA;");
    sTemp=replace(sTemp,"\n","&#xA;");
    sTemp=replace(sTemp,"\"","&quot;");

    return sTemp;
  }

  public static String editEncode(String s){
    String  re;
    if (s!=null&&!s.trim().equals("")){
      re=replace(s,"\"","&quot;");
    }else{
      re=s;
    }
    return re;
  }

  public static String Htmlbeizu(String s){
    String  re;
    if (s!=null&&!s.trim().equals("")){
      re=replace(s,"&","&amp;");
      re=replace(re,"<","&lt;");
      re=replace(re,">","&gt;");
      re=replace(re,"\r\n","&nbsp;&nbsp;&nbsp;&nbsp;");
      re=replace(re,"\n","&nbsp;&nbsp;&nbsp;&nbsp;");
      re=replace(re," ","&nbsp;");
      re=replace(re,"'","&#39");
      re=replace(re,"\"","&quot;");
    }
    else{
      re=s;
    }
    return re;
  }


  /**************************************************************************
   *功能：返回一子串在某字符串中出现的次数
   *参数：str- 待搜索的字符串
   *参数：substr- 要查找的子串（一般为字符）
   *返回值：任意参数为null返回-1，否则返回子串实际出现的次数
   **************************************************************************/
  public static int strFrequent(String str, String substr){
    if(str==null || substr==null)
      return -1;
    int frequent=0;
    int tempIndex=-1;
    int len=str.length();
    tempIndex=str.indexOf(substr);
    while(tempIndex!=-1){
      frequent++;
      if(tempIndex<len){
        str=str.substring(tempIndex+1,len);
        tempIndex=str.indexOf(substr);
        len=str.length();
      }
      else tempIndex=-1;
    }
    return frequent;
  }

  /**
     * 页面传递时进行为空处理及字符集转换
     * @param tempstr 字符串对象
     * @return 经过转换后的字符串
     */
    public static String getHtmlEncode(Object tempstr){
      String sTemp="";
      sTemp=nullToBlank(tempstr);
      return sTemp;
    }
    /**
     * 页面传递时进行为空处理及字符集转换
     * @param tempstr 字符串对象
     * @return 经过转换后的字符串
     */
    public static String getHtmlGBEncode(Object tempstr){
      String sTemp="";
      sTemp=alertCoding(nullToBlank(tempstr));
      return sTemp;
    }
    /**
     * 插入数据库时进行为空处理及字符集转换
     * @param tempstr 字符串对象
     * @return 经过转换后的字符串
     */
    public static String getSQLEncode(Object tempstr){
      return nullToBlank(tempstr);
    }
    /**
     * 插入数据库进行为空处理及字符集转换
     * @param tempstr 字符串对象
     * @return 经过转换后的字符串
     */
    public static String getSQLGBEncode(Object tempstr){
     String sTemp="";
     sTemp=sqlEncode(alertCoding(nullToBlank(tempstr)));
     return sTemp;
    }

    public String moneyFormat(double money){
     String sMoney="";
     sMoney=(String)df.format(money);
     if(sMoney.indexOf(".")==0){
        sMoney="0"+sMoney;
     }
     return sMoney;
   }

   public String moneyFormat(String money){
    if(money==null) return "0.00";
    String sMoney="";
    double moneyD=Double.parseDouble(money);
    sMoney=(String)df.format(moneyD);
    if(sMoney.indexOf(".")==0){
       sMoney="0"+sMoney;
    }
    return sMoney;
   }

   public String numFormat(String sNumber){
    if(sNumber==null) return "0.000";
    String sFormatNumber="";
    double moneyD=Double.parseDouble(sNumber);
    sFormatNumber=(String)dfs.format(moneyD);
    if(sFormatNumber.indexOf(".")==0){
       sFormatNumber="0"+sFormatNumber;
    }
    return sFormatNumber;
   }

   /**
   * 将字符串转换成Ascii码字符串，插入数据库时字段类型为text型时，可用此转换
   * @param String strInput:输入的字符串
   * @return:转换为Ascii编码后的字符串
   **/
  public static String toTureAsciiStr(String strInput){
    StringBuffer sb = new StringBuffer();
    byte[] bt = strInput.getBytes();
    for(int i =0 ;i<bt.length;i++){
      //是汉字去高位1
      if(bt[i]<0){
        sb.append((char)(bt[i]&0x7f));
      }
      //是英文字符 补0作记录
      else{
        sb.append((char)0);
        sb.append((char)bt[i]);
      }
    }
    return sb.toString();
  }

  /**
   * 类型为text型的字段，插入数据库时将字符串转换成Ascii码，可用此转换使其转换回
   * @param String strInput:输入的字符串
   * @return:转换编码后的字符串
   **/
  public static String unToTrueAsciiStr(String strInput){
    byte[] bt = strInput.getBytes();
    int i,l=0,length = bt.length,j=0;
    for(i = 0;i<length;i++){
      if(bt[i] == 0){
        l++;
      }
    }
    byte[] bt2 = new byte[length-l];
    for(i =0 ;i<length;i++){
      if(bt[i] == 0){
        i++;
        bt2[j] = bt[i];
      }
      else{
        bt2[j] = (byte)(bt[i]|0x80);
      }
      j++;
    }
    String strReturn = new String(bt2);
    return strReturn;
  }

  /**
   * 将一个字节数转换为一个十六进制字符串
   * @param b byte
   * @return String
   */
  public static String byteToHexString(byte b){
        String s[] = {
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
            "A", "B", "C", "D", "E", "F"
        };
        return String.valueOf(s[(b & 0xf0) >> 4]) + String.valueOf(s[b & 0xf]);
    }

    /**
     * 将一个字节数组转换为一个十六进制字符串
     * @param b byte[]
     * @return String
     */
    public static String byteToHexString(byte b[]){
        String s = "";
        for(int i = 0; i < b.length; i++)
            s = String.valueOf(s) + String.valueOf(byteToHexString(b[i]));

        return s;
    }

    /**
     * 将一个字符转换为一个字节
     * @param c char
     * @return byte[]
     */
    public static byte[] charToByte(char c){
        byte b[] = new byte[2];
        b[0] = (byte)(((short)c & 0xff00) >> 8);
        b[1] = (byte)((short)c & 0xff);
        return b;
    }

    /**
     * 将一个字节数组转换为一个字符
     * @param b byte[]
     * @return char
     */
    public static char byteToChar(byte b[]){
        return (char)((short)b[0] << 8 | (short)b[1] & 0xff);
    }

    /**
     * 将一个字符转换为一个十六进制字符串
     * @param c char
     * @return String
     */
    public static String charToHexString(char c){
        return byteToHexString(charToByte(c));
    }

    /**
     * 将一个十六进制的字符串转换为一个字节数组
     * @param s String
     * @return byte[]
     */
    public static byte[] hexStringToByte(String s){
        byte b[] = new byte[s.length() / 2];
        for(int i = 0; i < s.length() / 2; i++){
            String ss = s.substring(2 * i, 2 * i + 2);
            b[i] = (byte)Integer.parseInt(ss, 16);
        }
        return b;
    }

    /**
     * 将字符串转换为字节数组
     * @param s String
     * @return byte[]
     */
    public static byte[] stringToByte(String s){
        byte b[] = new byte[2 * s.length()];
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            b[2 * i + 0] = (byte)(((short)ch & 0xff00) >> 8);
            b[2 * i + 1] = (byte)((short)ch & 0xff);
        }

        return b;
    }

    /**
     * 将一个字节数组转换为一个字节字符串
     * @param b byte[]
     * @return String
     */
    public static String byteToString(byte b[]){
        byte t[] = new byte[2];
        char c[] = new char[b.length / 2];
        for(int i = 0; i < b.length / 2; i++){
            t[0] = b[2 * i + 0];
            t[1] = b[2 * i + 1];
            c[i] = byteToChar(t);
        }
        return new String(c);
    }

    /**
     * 用base64进行编码
     * @param str String
     * @return String
     */
    public static String base64Encode(String str)  {
       sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
       return encoder.encodeBuffer(str.getBytes()).trim();
   }

   /**
     * 用base64进行解码
     * @param str String
     * @return String
     */
   public static String base64Decodede(String str) {
       sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
       try {
           return new String(dec.decodeBuffer(str));
       }
       catch (IOException io) {
               throw new RuntimeException(io.getMessage(), io.getCause());
       }
   }

//   public static String convertString(String str){
//       String upStr = str.toUpperCase();
//       String lowStr = str.toLowerCase();
//       StringBuffer buf = new StringBuffer(str.length());
//
//       for(int i=0;i<str.length();i++){
//          if(str.charAt(i) == upStr.charAt(i)){
//            buf.append(lowStr.charAt(i));
//          }
//          else{
//            buf.append(upStr.charAt(i));
//          }
//   }
//    return buf.toString();
//}

   public static String filterQuot(String s){
          String rtn;
          rtn=replace(s,"'","`");
          return rtn;
  }
  public static String restoreQuot(String s){
          return replace(s,"`","'");
  }




  public static void main(String[] args){
   Encode enc=new Encode();
  }
}

